#include "Arduino.h"
#include "SPI.h"
#include "../lib/Ethernet/src/Ethernet.h"
#include "../lib/ArduinoHttpClient/src/ArduinoHttpClient.h"
#include "../lib/ArduinoJson/ArduinoJson.h"
#include "WString.h"
#include "Config.h"
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield

EthernetClient ethernetClient;

HttpClient httpClient = HttpClient(ethernetClient, "arduinojson.org", 80);

void setup() {
    pinMode(NetStatusPin, OUTPUT);
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    // wait for serial port to connect. Needed for native USB port only
    while (!Serial) {
    }
    //configure the CS pin
    EthernetClass::init(10);
    // start the Ethernet connection:
    Serial.println("Initialize Ethernet with DHCP:");
    if (EthernetClass::begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // Check for Ethernet hardware present
        if (EthernetClass::hardwareStatus() == EthernetNoHardware) {
            Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
        }
        if (EthernetClass::linkStatus() == LinkOFF) {
            Serial.println("Ethernet cable is not connected.");
            while (EthernetClass::linkStatus() == LinkOFF) {
                digitalWrite(NetStatusPin, HIGH);
                delay(500);
                digitalWrite(NetStatusPin, LOW);
                delay(500);
            }
        }
    } else {
        Serial.print("  DHCP assigned IP ");
        Serial.println(EthernetClass::localIP());
        digitalWrite(NetStatusPin, HIGH);
    }
    // give the Ethernet shield a second to initialize:
    delay(1000);
}

void loop() {
    Serial.println("making GET request");
    httpClient.get("/example.json");
    // read the status code and body of the response
    int statusCode = httpClient.responseStatusCode();
    String response = httpClient.responseBody();
    Serial.print("Status code: ");
    Serial.println(statusCode);
    Serial.print("Response: ");
    Serial.println(response);
    Serial.println("Wait five seconds");
    // Allocate the JSON document
    size_t capacity = JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(3) + 60;
    DynamicJsonDocument doc(capacity);
    deserializeJson(doc, httpClient);
    // Extract values
    Serial.println(F("Response:"));
    Serial.println(doc["sensor"].as<char *>());
    Serial.println(doc["time"].as<long>());
    Serial.println(doc["data"][0].as<float>(), 6);
    Serial.println(doc["data"][1].as<float>(), 6);
    httpClient.stop();
    delay(5000);
}